package com.excesys.exsecs.access.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.access.dto.AccessFloorDTO;
import com.excesys.exsecs.access.entity.AccessFloor;
import com.excesys.exsecs.access.mapper.AccessFloorMapper;
import com.excesys.exsecs.access.service.AccessFloorService;
import com.excesys.exsecs.access.util.JsonUtil;
import com.excesys.exsecs.access.vo.AccessFloorExcelVO;
import com.excesys.exsecs.access.vo.AccessFloorVO;
import com.excesys.exsecs.common.core.util.MsgUtils;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.vo.ErrorMessage;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.ParseException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 区域管理-楼层管理
 *
 * @author lxc
 * @date 2024-09-13 13:56:54
 */
@Service
public class AccessFloorServiceImpl extends ServiceImpl<AccessFloorMapper, AccessFloor> implements AccessFloorService {

    @Override
    public R importFloor(List<AccessFloorExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
        // 个性化校验逻辑
        List<AccessFloor> bamSFloors = this.list();

        int sucess = 0;
        int fail = 0;
        // 执行数据插入操作 组装 RoleDto
        for (AccessFloorExcelVO excel : excelVOList) {

            Set<String> errorMsg = new HashSet<>();

            boolean existSFloor = bamSFloors.stream()
                    .anyMatch(floor -> excel.getFloorCode().equals(floor.getFloorCode()));

            if (existSFloor) {
                errorMsg.add(MsgUtils.getMessage("bm.bamsfloor.code.existing", excel.getFloorCode()));
            }

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
            }
            else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
            }
            int num = insertFloor(excel);
            if (num == 1) {
                fail++;
            }
            else {
                sucess++;
            }
        }
        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.ok(sucess, "成功导入数量" + sucess + "。" + "存在" + fail + "重复");
    }

    private int insertFloor(AccessFloorExcelVO excel) {
        AccessFloor bamSFloor = new AccessFloor();
        List<AccessFloor> bamSFloors = baseMapper
                .selectList(Wrappers.<AccessFloor>lambdaQuery().eq(AccessFloor::getFloorCode, excel.getFloorCode()));
        if (bamSFloors.size() <= 0) {
            bamSFloor.setFloorCode(excel.getFloorCode());
            bamSFloor.setRemark(excel.getRemark());
            bamSFloor.setFloorCn(excel.getFloorCn());
            bamSFloor.setFloorEn(excel.getFloorEn());
            this.save(bamSFloor);
            return 0;
        }
        else {
            return 1;
        }
    }

    @Override
    public List<AccessFloorExcelVO> listFloor(AccessFloorDTO bamSFloor) {
        // List<BamSFloor> bamSFloors = this.list(Wrappers.emptyWrapper());
        QueryWrapper<AccessFloorDTO> query = QueryFloor(bamSFloor);
        List<AccessFloorVO> bamSFloors = baseMapper.getBamSFloorVos(query);

        // 转换成execl 对象输出
        return bamSFloors.stream().map(floor -> {
            AccessFloorExcelVO bamSFloorExcelVO = new AccessFloorExcelVO();
            BeanUtil.copyProperties(floor, bamSFloorExcelVO);
            return bamSFloorExcelVO;
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<AccessFloorVO> getFloorVosPage(Page page, AccessFloorDTO bamSFloorDTO) {
        QueryWrapper<AccessFloorDTO> query = QueryFloor(bamSFloorDTO);
        return baseMapper.getBamSFloorVosPage(page, query);
    }

    private QueryWrapper<AccessFloorDTO> QueryFloor(AccessFloorDTO bamSFloorDTO) {
        QueryWrapper<AccessFloorDTO> query = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(bamSFloorDTO.getFloorCn())) {
            query.and(e -> {
                e.like("bamf.floor_cn", bamSFloorDTO.getFloorCn());
            });
        }
        if (ObjectUtil.isNotNull(bamSFloorDTO.getFloorCode())) {
            query.and(e -> {
                e.like("bamf.floor_code", bamSFloorDTO.getFloorCode());
            });
        }
        if (ObjectUtil.isNotNull(bamSFloorDTO.getFloorPid())) {
            query.and(e -> {
                e.like("bamf.floor_pid", bamSFloorDTO.getFloorPid());
            });
        }
        query.orderByAsc("bamf.sort");
        return query;
    }

    @Override
    public List<AccessFloorVO> getFloorVos(AccessFloorDTO bamSFloorDTO) {
        QueryWrapper<AccessFloorDTO> query = QueryFloor(bamSFloorDTO);
        return baseMapper.getBamSFloorVos(query);
    }

    @Override
    public String GetFloorCodeBy(String code, int level, String suffix, int binary) throws ParseException {
        StringBuffer fc = new StringBuffer();
        for (int i = 0; i < level; i++) {
            // fc.concat("0");
            fc.append("0");
        }
        String fccode = "";
        String fl = code + suffix;
        List<AccessFloor> floors = baseMapper.selectList(Wrappers.<AccessFloor>lambdaQuery()
                .like(AccessFloor::getFloorCode, fl).orderByDesc(AccessFloor::getFloorCode));
        if (floors.size() > 0) {
            // String scode = floors.get(0).getFloorCode().replace(code, "");
            // scode = scode.replace(suffix, "");
            String scode = floors.get(0).getFloorCode().replace(fl, "");
            Format f = new DecimalFormat(fc.toString());
            Long ij = (Long) f.parseObject(scode);
            Long divisor = new Double(Math.pow(10, binary)).longValue();
            Long dig = ij / divisor;
            ij = dig + 1;
            fccode = fl + f.format(ij) + JsonUtil.addStrByCout("0", binary);
        }
        else {
            Format f = new DecimalFormat(fc.toString());
            Long ij = (Long) f.parseObject(fc.toString());
            ij = ij + 1;
            fccode = fl + f.format(ij) + "0";
        }
        return fccode;
    }
}